from typing import Optional, List, Union, Any
from pydantic import BaseModel, EmailStr, Field

from app.schemas.base import BaseSchema, TimestampMixin, TenantMixin, BaseEntity, PageQuery, StatusMixin, SoftDeleteMixin


class UserCreate(BaseModel):
    """创建用户 - 匹配RuoYi结构"""
    deptId: Optional[int] = Field(None, description="部门ID")
    userName: str = Field(..., min_length=1, max_length=30, description="用户账号")
    nickName: str = Field(..., min_length=1, max_length=30, description="用户昵称")
    userType: Optional[str] = Field('sys_user', max_length=10, description="用户类型")
    email: Optional[str] = Field('', max_length=50, description="用户邮箱")
    phonenumber: Optional[str] = Field('', pattern=r"^1[3-9]\d{9}$|^$", description="手机号码")
    sex: Optional[str] = Field('0', pattern=r"^[012]$", description="用户性别（0男 1女 2未知）")
    avatar: Optional[int] = Field(None, description="头像地址")
    password: str = Field(..., min_length=6, max_length=100, description="密码")
    status: Optional[str] = Field('0', pattern=r"^[01]$", description="帐号状态（0正常 1停用）")
    roleIds: Optional[List[int]] = Field([], description="角色ID列表")
    postIds: Optional[List[int]] = Field([], description="岗位ID列表")
    remark: Optional[str] = Field(None, max_length=500, description="备注")


class UserUpdate(BaseModel):
    """更新用户 - 匹配RuoYi结构"""
    deptId: Optional[int] = Field(None, description="部门ID")
    userName: Optional[str] = Field(None, min_length=1, max_length=30, description="用户账号")
    nickName: Optional[str] = Field(None, min_length=1, max_length=30, description="用户昵称")
    userType: Optional[str] = Field(None, max_length=10, description="用户类型")
    email: Optional[str] = Field(None, max_length=50, description="用户邮箱")
    phonenumber: Optional[str] = Field(None, pattern=r"^1[3-9]\d{9}$|^$", description="手机号码")
    sex: Optional[str] = Field(None, pattern=r"^[012]$", description="用户性别")
    avatar: Optional[int] = Field(None, description="头像地址")
    status: Optional[str] = Field(None, pattern=r"^[01]$", description="帐号状态")
    roleIds: Optional[List[int]] = Field(None, description="角色ID列表")
    postIds: Optional[List[int]] = Field(None, description="岗位ID列表")
    remark: Optional[str] = Field(None, max_length=500, description="备注")


class UserResponse(BaseSchema, TimestampMixin, TenantMixin):
    """用户响应 - 匹配RuoYi结构"""
    userId: int
    deptId: Optional[int] = None
    userName: str
    nickName: str
    userType: Optional[str] = None
    email: Optional[str] = None
    phonenumber: Optional[str] = None
    sex: Optional[str] = None
    avatar: Optional[int] = None
    status: str
    delFlag: Optional[str] = None
    loginIp: Optional[str] = None
    loginDate: Optional[str] = None
    remark: Optional[str] = None
    deptName: Optional[str] = None
    roles: List[dict] = []
    posts: List[dict] = []
    admin: bool = False


class UserListResponse(BaseModel):
    """用户列表响应"""
    total: int
    items: List[dict]


class ResetPasswordRequest(BaseModel):
    """重置密码请求 - Plus-UI兼容"""
    userId: int = Field(..., description="用户ID")
    password: str = Field(..., min_length=6, max_length=100, description="新密码")


class UpdateStatusRequest(BaseModel):
    """更新状态请求 - Plus-UI兼容"""
    userId: int = Field(..., description="用户ID")
    status: str = Field(..., pattern=r"^[01]$", description="状态（0正常 1停用）")


class ChangePasswordRequest(BaseModel):
    """修改密码请求"""
    oldPassword: str = Field(..., min_length=1, description="原密码")
    newPassword: str = Field(..., min_length=6, max_length=100, description="新密码")
    confirmPassword: str = Field(..., min_length=6, max_length=100, description="确认新密码")


class UpdateProfileRequest(BaseModel):
    """更新个人信息请求 - Plus-UI兼容"""
    nickName: Optional[str] = Field(None, max_length=30, description="用户昵称")
    email: Optional[str] = Field(None, max_length=50, description="用户邮箱")
    phonenumber: Optional[str] = Field(None, pattern=r"^1[3-9]\d{9}$|^$", description="手机号码")
    sex: Optional[str] = Field(None, pattern=r"^[012]$", description="用户性别")
    avatar: Optional[int] = Field(None, description="头像地址")


class ProfileResponse(BaseModel):
    """个人信息响应 - Plus-UI兼容"""
    userId: int
    userName: str
    nickName: Optional[str] = None
    email: Optional[str] = None
    phonenumber: Optional[str] = None
    avatar: Optional[int] = None
    sex: Optional[str] = None
    admin: bool
    loginDate: Optional[str] = None
    loginIp: Optional[str] = None
    deptId: Optional[int] = None
    deptName: Optional[str] = None
    roles: List[dict] = []
    posts: List[dict] = []
    createTime: Optional[str] = None


# Plus-UI 兼容的schemas
class UserInfo(BaseModel):
    """用户信息"""
    user: dict  # 暂时使用dict，避免前向引用
    roles: List[str]
    permissions: List[str]


class UserQuery(PageQuery):
    """用户查询对象类型"""
    userName: Optional[str] = None
    nickName: Optional[str] = None
    phonenumber: Optional[str] = None
    status: Optional[str] = None
    deptId: Optional[Union[str, int]] = None
    roleId: Optional[Union[str, int]] = None
    userIds: Optional[Union[str, int, List[Union[str, int]]]] = None


class UserVO(BaseEntity):
    """用户返回对象"""
    userId: Union[str, int]
    tenantId: str
    deptId: int
    userName: str
    nickName: str
    userType: str
    email: str
    phonenumber: str
    sex: str
    avatar: str
    status: str
    delFlag: str
    loginIp: str
    loginDate: str
    remark: str
    deptName: str
    roles: List[dict] = []  # 暂时使用dict，避免循环导入
    roleIds: Any
    postIds: Any
    roleId: Any
    admin: bool


class UserForm(BaseModel):
    """用户表单类型"""
    id: Optional[str] = None
    userId: Optional[str] = None
    deptId: Optional[int] = None
    userName: str
    nickName: Optional[str] = None
    password: str
    phonenumber: Optional[str] = None
    email: Optional[str] = None
    sex: Optional[str] = None
    status: str
    remark: Optional[str] = None
    postIds: List[str]
    roleIds: List[str]


class UserInfoVO(BaseModel):
    """用户信息VO"""
    user: Optional[UserVO]
    roles: List[dict] = []  # 暂时使用dict，避免循环导入
    roleIds: List[str]
    posts: List[dict] = []  # 暂时使用dict，避免循环导入
    postIds: List[str]
    roleGroup: str
    postGroup: str


class ResetPwdForm(BaseModel):
    """重置密码表单"""
    oldPassword: str
    newPassword: str
    confirmPassword: str


# 解决前向引用
UserVO.model_rebuild()
UserInfoVO.model_rebuild()